﻿using System.Threading;
using mmCore.Classes;
using mmImdbProvider;
using NUnit.Framework;
using System.Collections.Generic;

namespace mmTests
{
    [TestFixture]
    public class ImdbTest
    {
        private bool _mFinished = false;
        private bool _mFound = false;

        private int _mWaited = 0;

        private const int LoopWait = 1000;
        private const int MaxWait = 60000;

        private SearchMovieResult _mSmr = null;
        private Movie _mMovie = null;

        [Test]
        public void TestImdbSearch1()
        {
            var dbs = new ImdbSearch();
            dbs.OnFound += dbs_OnFound;
            dbs.Search("house");

            while(!_mFinished)
            {
                Thread.Sleep(LoopWait);
                _mWaited += LoopWait;
                if (_mWaited >= MaxWait)
                {
                    Assert.Fail("Movies searching timeout!");
                }
            }

            Assert.AreEqual(_mFound, true);
        }

        void dbs_OnFound(List<SearchMovieResult> results)
        {
            _mFound = results.Count > 0;
            _mFinished = true;
        }

        [Test]
        public void TestImdbDetails()
        {
            var dbs = new ImdbSearch();
            dbs.OnFound += dbs_OnFound2;
            dbs.Search("How I Met Your Mother");

            while (_mSmr == null)
            {
                Thread.Sleep(LoopWait);
                _mWaited += LoopWait;
                if (_mWaited >= MaxWait)
                {
                    Assert.Fail("Movies searching timeout!");
                }
            }

            var dbd = new ImdbDetails();
            dbd.OnFinished += dbd_OnFinished;
            dbd.Read(_mSmr);

            while(_mMovie == null)
            {
                Thread.Sleep(LoopWait);
                _mWaited += LoopWait;
                if (_mWaited >= MaxWait)
                {
                    Assert.Fail("Movies searching timeout!");
                }
            }

            Assert.AreNotEqual(_mMovie.Id, null);
            Assert.AreNotEqual(_mMovie.Id, string.Empty);
        }

        private void dbd_OnFinished(Movie movie)
        {
            Assert.AreNotEqual(movie, null);
            var ed = new ImdbEpisodeReader();
            ed.OnFinished += ed_OnFinished;
            ed.Read(movie);
        }

        void ed_OnFinished(Movie movie)
        {
            Assert.AreNotEqual(movie, null);
            _mMovie = movie;
        }

        private void dbs_OnFound2(List<SearchMovieResult> results)
        {
            if(results.Count >= 1)
            {
                _mSmr = results[0];
            }
            else
            {
                _mSmr = new SearchMovieResult();
            }
        }
    }
}
